package cn.enine.tbcharge.ui;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;

import org.litepal.LitePal;

import java.math.BigDecimal;
import java.util.List;
import java.util.UUID;

import cn.enine.tbcharge.R;
import cn.enine.tbcharge.base.MyBaseActivity;
import cn.enine.tbcharge.pojo.AppSfMain;
import cn.enine.tbcharge.pojo.AppSfSub;
import cn.enine.tbcharge.pojo.AppXmpy;
import cn.enine.tbcharge.pojo.RetMsg;
import cn.enine.tbcharge.util.DateConvert;
import cn.enine.tbcharge.util.HttpUrl;
import cn.enine.tbcharge.util.MyToastUtil;
import cn.enine.tbcharge.util.NetWorkUtils;
import cn.enine.tbcharge.util.RegexUtils;
import cn.enine.tbcharge.util.SharedPreferencesUtils;
import cn.enine.tbcharge.util.StringUtils;
import cn.enine.tbcharge.util.UserClient;
import cn.pedant.SweetAlert.SweetAlertDialog;

public class SfSubActivity extends MyBaseActivity {

    //标题
    TextView title, uname,xmid;
    LinearLayout back;
    Context con = SfSubActivity.this;

    private EditText xmname;
    private EditText fy;
    AppSfSub obj;
    boolean isadd=false;//是否是新添加
    String url="",mainid ="";
    AppXmpy appXmpy;

    @Override
    protected void initUI() {
        setContentView(R.layout.activity_sf_sub);
        mainid = getIntent().getStringExtra("mainid");
        Log.i("SfSubActivity", mainid+"==================");
        if (getIntent().getStringExtra("type").equals("edit")) {
            obj = (AppSfSub) getIntent().getExtras().getSerializable("b");
            isadd=false;
            init(obj);
        }else {
            isadd=true;
            obj = new AppSfSub();
            init(obj);
        }
    }

    private void init(final AppSfSub obj){
        //姓名
        xmname = (EditText) findViewById(R.id.xmname);
        xmname.requestFocus();
        if (obj != null && !StringUtils.isEmpty(obj.getXmname())) {
            xmname.setText(obj.getXmname());
        }
        xmname.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!NetWorkUtils.isNetworkConnected(con)) {
//                    MyToastUtil.ShowToast(con, "联网失败！");
                    Bundle bundle = getIntent().getExtras();
                    if (null != bundle.getString("type") && "add".equals(bundle.getString("type"))) {
                        startActivityForResult(new Intent(con, ChooseXmActivity.class).putExtra("cname", "SfSubActivity.class"), 1);
                    }
                }else {
                    Bundle bundle = getIntent().getExtras();
                    if (null != bundle.getString("type") && "add".equals(bundle.getString("type"))) {
                        startActivityForResult(new Intent(con, ChooseXmActivity.class).putExtra("cname", "SfSubActivity.class"), 1);
                    }
                }

            }
        });
        xmid = (TextView) findViewById(R.id.xmid);
        if (obj != null && !StringUtils.isEmpty(obj.getXmid())) {
            xmid.setText(obj.getXmid());
        }
        fy = (EditText) findViewById(R.id.fy);
        if (obj != null && !"".equals(obj.getFy())&& null!=obj.getFy()) {
            fy.setText(obj.getFy()+"");
        }
        back = (LinearLayout) findViewById(R.id.back);

        title = (TextView) findViewById(R.id.title);
        uname = (TextView) findViewById(R.id.uname);
        title.setText("收费明细信息");
        uname.setText("保存");
        uname.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String xmnameText = xmname.getText().toString();
                String xmidText = xmid.getText().toString();
                String fyText = fy.getText().toString();

                if(null == xmnameText || "".equals(xmnameText) || "点我选择".equals(xmnameText)){
                    MyToastUtil.ShowToast(con,"请选择收费项目");
                }else if(null == fyText || "".equals(fyText)){
                    MyToastUtil.ShowToast(con,"请填写费用");
                }else if(!RegexUtils.isDyling(fyText)){
                    MyToastUtil.ShowToast(con,"请正确填写费用");
                }else if (NetWorkUtils.isNetworkConnected(con)) {  ///网络连接
                    RequestParams ps = new RequestParams();
                    if (isadd) {
                        url = HttpUrl.SaveSfsub;
                    } else {
                        ps.add("entity.NID", obj.getNid());
                        url = HttpUrl.EditSfsub;
                    }
                    ps.add("entity.MAINID", mainid);
                    ps.add("entity.XMID", xmidText);
                    ps.add("entity.XMNAME", xmnameText);
                    ps.add("entity.FY", fyText);
                    ps.add("token", SharedPreferencesUtils.getParam(con, "token", "").toString());
                    ps.add("type", "2");
                    UserClient.get(url, ps, new AsyncHttpResponseHandler() {
                        @Override
                        public void onSuccess(String content) {
                            super.onSuccess(content);
                            MyToastUtil.ShowToast(con, "成功");
                            finish();
                        }
                        @Override
                        public void onFailure(Throwable error) {
                            super.onFailure(error);
//                            MyToastUtil.ShowToast(con, "失败");
                            saveAppSubNoNet(fyText==null || "".equals(fyText) ? "0" :fyText);
                        }
                    });
                } else {
                    saveAppSubNoNet(fyText==null || "".equals(fyText) ? "0" :fyText);
                }
            }
        });

    }
    private void saveAppSubNoNet(String fytextVal){
        String nid = UUID.randomUUID().toString().replaceAll("-","").toUpperCase();
        obj.setNid(nid);
        obj.setMainid(mainid);
//        obj.setFy(fyText==null || "".equals(fyText) ? "0" :fyText);
        obj.setFy(fytextVal);
        obj.setAddtime(DateConvert.getDateString(DateConvert.YMDHMS));
        obj.save();
        List<AppSfMain> mainlist = LitePal.where("nid = ?", mainid).find(AppSfMain.class);
        if(null != mainlist && mainlist.size()==1){
            AppSfMain appSfMain = (AppSfMain)mainlist.get(0);
            BigDecimal oldTotal = new BigDecimal(appSfMain.getTotalfy()==null || "".equals(appSfMain.getTotalfy()) ? "0" : appSfMain.getTotalfy());
            BigDecimal newTotal = oldTotal.add(new BigDecimal(fytextVal==null || "".equals(fytextVal) ? "0" :fytextVal));
            appSfMain.setTotalfy(newTotal+"");
            appSfMain.update(appSfMain.getId());
        }
        MyToastUtil.ShowToast(con, "成功");
        finish();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (data == null) {

        } else {
            Log.i("requestCode====",requestCode+"");
            appXmpy = (AppXmpy) data.getExtras().getSerializable("appXmpy");
            getObject();
        }
    }

    public void getObject() {
        RequestParams ps = new RequestParams();
        ps.add("token", SharedPreferencesUtils.getParam(con, "token", "").toString());
        ps.add("type", "2");
        ps.add("id", appXmpy.getNid());
        UserClient.get(HttpUrl.GetXm, ps, new AsyncHttpResponseHandler() {
            @Override
            public void onSuccess(String content) {
                super.onSuccess(content);
                RetMsg ret = JSON.parseObject(content, RetMsg.class);
                if (ret.getCode().equals("200")) {
                    JSONObject jsonObject = JSON.parseObject(ret.getRd());
                    obj = new AppSfSub();
                    init(obj);
                    obj.setXmid(jsonObject.getString("NID"));
                    obj.setXmname(jsonObject.getString("YYXMMC"));
                    xmname.setText(jsonObject.getString("YYXMMC"));
                    xmid.setText(jsonObject.getString("NID"));
                    isadd = true;
                } else {
                    new SweetAlertDialog(con, SweetAlertDialog.ERROR_TYPE).setTitleText("提示")
                            .setContentText(ret.getInfo())
                            .setConfirmClickListener(new SweetAlertDialog.OnSweetClickListener() {
                                @Override
                                public void onClick(SweetAlertDialog sweetAlertDialog) {
                                    finish();
                                }
                            }).show();
                }

            }
            @Override
            public void onFinish() {
                super.onFinish();
            }

            @Override
            public void onFailure(Throwable error) {
                super.onFailure(error);
                isadd = true;
                obj = new AppSfSub();
                init(obj);
                List<AppXmpy> jlist = LitePal.where("nid = ?", appXmpy.getNid()).order("nid").find(AppXmpy.class);
                if(null != jlist && jlist.size()>=0){
                    AppXmpy appXmpy = (AppXmpy)jlist.get(0);

                    obj.setXmid(appXmpy.getNid());
                    obj.setXmname(appXmpy.getYyxmmc());
                    xmname.setText(appXmpy.getYyxmmc());
                    xmid.setText(appXmpy.getNid());
                }
            }
        });
    }


    @Override
    protected void initData() {

    }

    @Override
    protected void initListener() {
        back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
    }
}
